#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        paramModel.py
# Author:    KuKei
# Create Date: 2011-10-22
# Description: 参数部分模型
# Modify Date: 2011-10-22

from django.db import models
from sd.cms.models import BaseModel
from sd.cms.lib import Params
from sd.cms.lib.decorator import cacheData
from sd import settings
from django.core.files.storage import FileSystemStorage

class GlobalManager(models.Manager):
    @cacheData(key=Params.GLOBAL)
    def toOptions(self, orgList=None, empty=None):
        retList = [empty] if empty else []        
        fs = FileSystemStorage(settings.TEMPLATE_DIRS[0])
        dirList = fs.listdir('')[0]
        for e in dirList:
            if e.find('.') < 0 :
                retList.append(eval('("'+e+'","'+e+'")'))
        return retList
    
class Global(BaseModel):
    #===============================================================================
    # CACHE_LEVEL_CHOICES说明：数据越大说明可以缓存的内容越多
    # 0：不缓存；
    # 1：1级缓存，只缓存单页，如文章，产品等；还缓存标签，数据等
    # 2：2级缓存，可以缓存1级的内容以及列表
    #===============================================================================
    CACHE_LEVEL_CHOICES = (
        (-1, '不缓存.'),
        (1, '一级缓存.'),
        (2, '二级缓存.'),
    )
    
    title = models.CharField("标题", max_length=50, help_text="", null=True)
    subtitle = models.CharField("副标题", max_length=100, help_text="", null=True)
    keywork = models.CharField("关键字", max_length=100, help_text="", null=True)
    describe = models.TextField("描述", help_text="", null=True)
    sumlength = models.IntegerField("摘要长度", help_text="需要保存摘要的文字长度", null=True)
    cachelevel = models.IntegerField("缓存级别", choices=CACHE_LEVEL_CHOICES, null=True)
    theme = models.CharField("主题", max_length=50, help_text="站点的显示风格", null=True)
    objects = GlobalManager()

#全局参数
#系统级参数不允许删除增加
class GlobalParam(BaseModel):
    STYLE_CHOICES = (
        (1, '正常'),
        (2, '中等'),
        (3, '大型'),
    )
    kind = models.IntegerField("类别", max_length=50)
    code = models.CharField("编码", max_length=50)
    name = models.CharField("名称", max_length=50)
    value = models.TextField("值")
    describe = models.TextField("简介", null=True, blank=True)
    orderby = models.IntegerField("显示顺序")
    style = models.IntegerField("值风格", choices=STYLE_CHOICES, default=1)
    autoload = models.BooleanField("自动加载", default=True)
    issys = models.IntegerField("是否为系统级参数", max_length=50, default=-1)
    

class ParamManager(models.Manager):
    @cacheData(key=Params.PARAM)
    def toOptions(self, kind, orgList=None, empty=None):
        retList = [empty] if empty else []
        orgList =  orgList if orgList else list(Param.objects.filter(kind=kind).order_by('orderby'))
        for e in orgList:
            retList.append(eval('('+str(e.id)+',"'+e.name+'")'))
        return retList
#参数
#说明：不同的code代表不同的参数组，以下为说明
#1：栏目模型；
class Param(BaseModel):
    kind = models.IntegerField("类型")
    code = models.CharField("编码", max_length=50)
    name = models.CharField("名称", max_length=50)
    value = models.CharField("参数值", max_length=50)
    describe = models.TextField("描述", null=True)
    orderby = models.IntegerField("显示顺序")
    isdisplay = models.BooleanField("是否显示", default=True)
    preserve1 = models.IntegerField("保留1", null=True)
    preserve2 = models.CharField("保留2", max_length=50, null=True)
    preserve3 = models.CharField("保留3", max_length=50, null=True)
    preserve4 = models.TextField("保留4", null=True)
    objects = ParamManager()
    
    def __unicode__(self):
        return self.name

class ColumManager(models.Manager):
    @cacheData(key=Params.COLUMN)
    def toOptions(self, orgList=None, empty=None):
        retList = [empty] if empty else []
        orgList =  orgList if orgList else list(Column.objects.all().order_by('orderby'))
        for e in orgList:
            retList.append(eval('('+str(e.id)+',"'+e.name+'")'))
        return retList

#栏目
#默认情况为一级使用方式，即无子栏目；
#栏目一般分为新闻，文章，产品介绍，图片，视频，音乐等
class Column(BaseModel):
    name = models.CharField("栏目名称", max_length=50)
    value = models.CharField("栏目值", max_length=50)
    parent = models.IntegerField("父栏目", blank=True, null=True)
    level = models.IntegerField("层级", blank=True, null=True)
    model = models.ForeignKey(Param, verbose_name="模型", limit_choices_to = {'kind': 1})
    describe = models.TextField("栏目简介", null=True)
    orderby = models.IntegerField("显示顺序")
    isdisplay = models.BooleanField("是否显示", blank=True)
    objects = ColumManager()
    
    def __unicode__(self):
        return self.name
    

#目录
#默认情况分为2级目录
#目录是用来将内容分类的
class CatalogManager(models.Manager):
    def valueCount(self, val='', id=None):
        return self.exclude(id=id).filter(value=val).count() if id else self.filter(value=val).count()
    
    @cacheData(key=Params.CATALOGS)
    def toOptions(self, orgList=None, empty=None):
        retList = [empty] if empty else []
        orgList =  orgList if orgList else list(Catalog.objects.filter(level=10).order_by('orderby')) 
        for e in orgList:
            retList.append(eval('('+str(e.id)+',"'+e.name+'")'))
        return retList
    
    @cacheData(key=Params.CATALOGS)
    def toOptionsByModel(self, model, level=20, empty=None, orgList=None):
        retList = [empty] if empty else []
        paramModel = list(Param.objects.filter(kind=1, value=model))
        if len(paramModel)==1:
            columnList = list(paramModel[0].column_set.all())
            orgList =  orgList if orgList else list(Catalog.objects.filter(level=level, column__in=columnList).order_by('orderby')) 
            for e in orgList:
                retList.append(eval('('+str(e.id)+',"'+e.name+'")'))
        return retList
    
class Catalog(BaseModel):
    CATALOG_KIND_CHOICES = (
        (1, '目录.'),
        (2, '菜单.'),
    )
    CATALOG_LEVEL_CHOICES = (
        (10, '一级目录.'),
        (20, '二级目录.'),
    )

    name = models.CharField("目录名称", max_length=50)
    value = models.CharField("目录值", max_length=50)
    kind = models.IntegerField("类型", max_length=1, choices=CATALOG_KIND_CHOICES)
    level = models.IntegerField("层级", choices=CATALOG_LEVEL_CHOICES)
    parent = models.IntegerField("上级目录")
    islast =  models.BooleanField("终级目录", default=False)
    column = models.ForeignKey(Column, verbose_name="所属栏目")
    cnt = models.IntegerField("子菜单个数", default=0)
    orderby = models.IntegerField("显示顺序")
    isdisplay = models.BooleanField("是否显示", default=True)
    objects = CatalogManager()
    
    def __unicode__(self):
        return self.name
    

#标签
class Tag(BaseModel):
    name = models.CharField("标签名称", max_length=50)
    cnt = models.IntegerField("内容个数", default=0)
    